package com.projectxxxxxxxxxx.screens;

import java.util.HashMap;
import java.util.Map;

import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

import com.projectxxxxxxxxxx.utils.ScheduledTask;
import com.projectxxxxxxxxxx.widget.RoboAppWidgetProvider;
import com.projectxxxxxxxxxx.widget.RoboAppWidgetProvider4x4;
import com.projectxxxxxxxxxx.widget.WidgetReceiver;

public abstract class Screen {
    protected final Context context;
    protected final int id; // screen id on layout
    protected final Map<String, Integer> actionsView; // link between view in
                                                    // screen and action for
                                                    // update widget

    public static int currentScreen;
    protected ScheduledTask pingTimer;
    protected String widgetClassName;

    public Screen(final Context context, final int id, String widgetClassName) {
        this.context = context;
        this.id = id;
        this.actionsView = new HashMap<String, Integer>();
        pingTimer = new ScheduledTask.DefaultScheduledTask();
        this.widgetClassName = widgetClassName;
    }

    public abstract void updateAllView(final RemoteViews views);

    public abstract void updateView(final Intent intent, final String action, final RemoteViews views);

    public void addNewViewAction(final int keyId, final String action) {
        actionsView.put(action, keyId);
    }

    public void removeViewAction(final String action) {
        actionsView.remove(action);
    }

    public void requestRedraw(final String action) {
        final Intent intent = new Intent(action);
        context.sendBroadcast(intent);
    }

    public int getViewAction(final String action) {
        return actionsView.get(action).intValue();
    }

    public void stopUpdate() {
        pingTimer.cancel();
    }

    public void updateWidget(final RemoteViews views) {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        ComponentName componentName = new ComponentName(context, widgetClassName);
        final int[] widgetIds = appWidgetManager.getAppWidgetIds(componentName);

        if (widgetIds == null || widgetIds.length == 0) {
            return;
        }

        final int length = widgetIds.length;
        for (int i = 0; i < length; i++) {
            int widgetId = widgetIds[i];
            appWidgetManager.updateAppWidget(widgetId, views);
        }
    }
}
